#!/bin/bash

<<comment
自行准备环境如下
web1：eth0->192.168.88.100/24

web2：eth0->192.168.88.200/24

client1: eth0->192.168.88.10/24
提前做好免密登陆(可参考lvs.sh脚本文件的免密配置)
自行配好yum
此脚本在web1执行
comment

ip1=192.168.88.100
ip2=192.168.88.200
vip=192.168.88.80
cip=192.168.88.10
file1="/etc/keepalived/keepalived.conf"
# 在web上安装keepalived
yum -y install keepalived httpd &> /dev/null
ssh $ip2 "yum -y install keepalived httpd" &> /dev/null
echo "apache web server1" > /var/www/html/index.html
ssh $ip2 "echo 'apache web server2' > /var/www/html/index.html"

# 修改配置文件

sed -i '/router_id/s/LVS_DEVEL/web1/' $file1
sed -i '12a\   vrrp_iptables' $file1
sed -i '31,33d' $file1 && sed -i "/virtual_ipaddress/a   $vip/24" $file1
sed -i '34,$d' $file1
# 起服务

systemctl start keepalived httpd
scp $file1 $ip2:$file1 > /dev/null
ssh $ip2 "sed -i '/router_id/s/web1/web2/' $file1"
ssh $ip2 "sed -i '/priority/s/100/80/' $file1"  # 更改优先级
ssh $ip2 "sed -i '/state/s/MASTER/BACKUP/' $file1"  # 更改状态为备
ssh $ip2 "systemctl start keepalived httpd"

# 验证
systemctl stop keepalived
sleep 1
[ $(ssh $cip "curl -s http://$vip" | cut -d' ' -f3) == "server2" ] && echo -e "\033[36m高可用的web集群配置成功\033[0m" && systemctl start keepalived
